package cn.shenzz.suixiang.link.leetcode_02_07;

import cn.shenzz.suixiang.link.ListNode;

public class Solution {

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA, curB = headB;
        int lengthA = 0, lengthB = 0;

        while (curA != null) {
            ++lengthA;
            curA = curA.next;
        }
        while (curB != null) {
            ++lengthB;
            curB = curB.next;
        }

        curB = headB;
        curA = headA;


        if (lengthB > lengthA) {
            int tempLength = lengthA;
            lengthA = lengthB;
            lengthB = tempLength;

            ListNode tempListNode = curA;
            curA = curB;
            curB = tempListNode;
        }
        int gap = lengthA - lengthB;
        while (gap-- > 0) {
            curA = curA.next;
        }

        while (curA != null && curB != null) {
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}